<template>
    <div class="farm-container"> 
        <headerBar :title="title"></headerBar>
        <div class="g_card_important my-status">
          <div class="welcome_title_import">绑定账号,即刻挂卡!（内测中）</div>
            <div style="color: #fff; margin: 20px 0 10px 0;" v-if="result.login_name">
            当前挂卡账号： {{result.login_name}}
            </div>
            <div style="color: #fff; margin: 10px 0 30px 0;">
            您的挂卡状态： {{result.status_display || '请先绑定账号'}}
            </div>
          <div class="status-bar">
            <van-button style="background-color: #4b0; border-color: #4b0;" class="after-button" size="small" @click="showAccount">绑定账号</van-button>
            <van-button class="after-button" size="small" @click="startAccount">启动挂卡</van-button>
            <van-button style="background-color: #F44336; border-color: #F44336;" class="after-button" size="small" @click="stopAccount">停止挂卡</van-button>
            <van-button style="background-color: #FFF; border-color: #FFF;" class="after-button" size="small" @click="refreshAccount">刷新状态</van-button>
          </div>
        </div>
        <!-- // 挂卡的时候显示相关挂卡内容 -->
        <div class="g_card_important my-status" v-if="showNow">
          <div class="welcome_title_import">
            当前在挂游戏
          </div>
          <div class="games-to-farm" v-for="item in CurrentGamesFarming" :key="item.AppId">
            <div class="card-img-div">
              <img :src="item.img" class="card-img"/>
            </div>
            <div class="card-main">
              <div>游戏名称: {{item.GameName}}</div>
              <div>游戏时间: {{item.HoursPlayed.toFixed(1) }} 小时</div>
              <div>剩余卡牌: {{item.CardsRemaining}} 张</div>
            </div>
          </div>
        </div>

        <div class ="g_card_important my-status" v-if="!showBind">
          <div class="welcome_title_import">剩余可挂游戏</div>
          <div class="games-to-farm" v-for="item in cardsStatus.GamesToFarm" :key="item.AppId">
            <div class="card-img-div">
              <img :src="item.img" class="card-img"/>
            </div>
            <div class="card-main">
              <div>游戏名称: {{item.GameName}}</div>
              <div>游戏时间: {{item.HoursPlayed.toFixed(1) }} 小时</div>
              <div>剩余卡牌: {{item.CardsRemaining}} 张</div>
            </div>
          </div>
        </div>
        <van-dialog
                v-model="showSteam"
                title="绑定STEAM账号"
                class="main-input"
                show-cancel-button
                :before-close="beforeCloseBind"
        >
        <input v-model="username" required clearable label="steam用户名" placeholder="steam用户名" class="inputcenter">
        <input v-model="password" type="password" required clearable label="steam密码" placeholder="steam密码" class="inputcenter">
        </van-dialog>
         <van-dialog
                v-model="dialog_show"
                title="请输入您的手机/邮箱令牌码"
                :before-close="beforeClose"
                class="main-input"
                >
                <input v-model="short_code" placeholder="" class="inputcenter">
        </van-dialog>
        <Bottom></Bottom>
    </div>
</template>

<script>
/* eslint-disable */
import Bottom from "@/components/bottom";
import headerBar from "@/components/headerBar";
import {
  getAllBot,
  createBot,
  getBotStatus,
  startBot,
  robotInput,
  robotStop
} from "@/apis/apis";
import { stringify, dateFormat } from "@/utils";
import { mapState } from "vuex";
// 现在的充值部分逻辑为不定额充值,也就是说现在我们的充值方式为类似FARMSKINS的方式
export default {
  filters: {
    dateFormatFilter(value, Format) {
      if (typeof value == "undefined") return "";
      if (typeof value == "number") value = new Date(value);
      if (typeof value == "string") value = new Date(value);
      return dateFormat(value, Format);
    }
  },
  data() {
    return {
      title: '云挂卡',
      timer: null,
      botId: null,
      dialog_show: false,
      short_code: null,
      showBind: false,
      cardsStatus: [],
      username: '',
      password: '',
      showSteam: false,
      showNow: false,
      CurrentGamesFarming: [],
      result: []
    };
  },
  components: {
    Bottom,
    headerBar
  },
  computed: {
    ...mapState({
      isLogined: "isLogined",
      userInfo: "detail"
    })
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getAllBot()
    },
    showAccount() {
      this.showSteam = true
    },
    refreshAccount() {
      window.location.reload();
    },
    stopAccount () {
      if(!this.botId) {
        return this.$toast({
          message: "请先绑定账号",
          position: "bottom"
        });
      }
      robotStop(this.botId).then(res => {
        if(res._status === 0) {
          this.$toast({
            message: "暂停挂卡成功",
            position: "bottom"
          });
          window.location.reload();
        }
      })
    },
    startAccount () {
      if(!this.botId) {
        return this.$toast({
          message: "请先绑定账号",
          position: "bottom"
        });
      }
      startBot(this.botId).then(res => {
        if(res._status === 0) {
          this.$toast({
            message: "启动挂卡成功",
            position: "bottom"
          });
          window.location.reload();
        } else {
          this.$toast({
            message: "启动挂卡失败，请重新绑定",
            position: "bottom"
          });
        }
      })
    },
    beforeCloseBind(action, done) {
      if(action == "confirm") {
        if(!this.username) {
          done()
          return this.$toast({
            message: "请输入账号",
            position: "bottom"
          });
        }
        var reg = /^[0-9a-zA-Z]+$/
        if(!reg.test(this.username)) {
          done()
          return this.$toast({
            message: "请输入正确的账号格式",
            position: "bottom"
          });
        }
        if(!this.password) {
          done()
          return this.$toast({
            message: "请输入密码",
            position: "bottom"
          });
        }
        this.createBot()
        done()
      } else {
        done()
      }
    },
    // 
    beforeClose(action, done) {
      if (action === "confirm") {
        let data = {
          code: this.short_code.toUpperCase()
        }
        //这里输入完之后还他妈要轮训
        if(this.short_code.length !== 5) {
          done()
          return this.$toast({
            message:'请输入正确的五位令牌',
            position: "bottom"
          })
        }
        console.log('rere', this.botId)
        robotInput(data, this.botId).then(res => {
          console.log(res)
           this.timer = setInterval(() => {
            getBotStatus(this.botId).then((res) => {
              // 大于1的时候终止轮训
              // CREATE = 0              # 创建
              // TRY_START = 1           # 尝试启动
              // RUN = 2                 # 运行中
              // SERVER_OFF = 3          # 服务器关闭
              // STOP = 4                # 停止
              // # error
              // NEED_GUARD_CODE = 1063  # 需要SteamGuardCode(邮箱验证码)
              // NEED_TWO_FACTOR = 1085  # 需要TwoFactorAuthentication(手机验证码)'
              if (res.status > 1) {
                console.log(res.status)
                switch (res.status) {
                  case 0:
                    console.log('创建')
                    break;
                  case 1:
                    console.log('尝试启动')
                    break;
                  case 2:
                    console.log('运行中')
                    clearInterval(this.timer)
                    // 正常启动后应该reload
                    window.location.reload();
                    this.timer = null;
                    break;
                  case 3:
                    console.log('服务器关闭')
                    clearInterval(this.timer)
                    this.timer = null;
                    break;
                  case 4:
                    console.log('停止')
                    clearInterval(this.timer)
                    this.timer = null;
                    break;
                  case 1005:
                    console.log('无效的密码')
                    this.showBind = true
                    // 密码无效后的操作应该是让用户再次输入密码
                    clearInterval(this.timer)
                    this.timer = null;
                    return this.$toast({
                      message: "密码无效,请重新绑定",
                      position: "bottom"
                    });
                  case 1063:
                    console.log('需要邮箱验证码')
                    clearInterval(this.timer)
                    this.timer = null;
                    this.$toast({
                      message: "请输入正确的邮箱验证码",
                      position: "bottom"
                    });
                    break;
                  case 1084:
                    console.log('请求限速')
                    clearInterval(this.timer)
                    this.timer = null;
                    this.$toast({
                      message: "请求频率过多，请稍后再试",
                      position: "bottom"
                    });
                    break;
                  case 1085:
                    console.log('需要手机验证码')
                    clearInterval(this.timer)
                    this.timer = null;
                    this.$toast({
                      message: "请输入正确的手机验证码",
                      position: "bottom"
                    });
                    break;          
                  default:
                    break;
                }
              }
            });
          }, 1250);
        })
        this.$toast({
            type:'loading',
            message:'正在验证令牌'
        })
        done();
      }
    },
    getAllBot() {
      // 刚刚进来的时候查询所有bot
      getAllBot().then(res => {
        if(res._status === 0 && res.objects.length > 0) {
          console.log(res)
          this.botId = res.objects[0].resource_uri
          this.result = res.objects[0]
          // 如果有cards_farmer说明用户还是在ASF里面有配置信息的
          if(res.objects[0].cards_farmer) {
            // 这个时候ASF已经启动了了
            // 创建的时候也要对当前ASF的状态进行判断
            switch (res.objects[0].status) {
              case 0:
                console.log('创建')
                break;
              case 1:
                console.log('尝试启动')
                break;
              case 2:
                console.log('运行中')
                this.CurrentGamesFarming = res.objects[0].cards_farmer.CurrentGamesFarming
                this.showNow = true
                // 运行中显示自己当前挂卡
                break;
              case 3:
                console.log('服务器关闭')
                break;
              case 4:
                console.log('停止')
                break;
              case 1005:
                console.log('无效的密码')
                // 用户刚进来的的时候密码无效让他重新绑定
                this.showBind = true
                break;
              case 1063:
                console.log('需要邮箱验证码')
                // 用户刚进来的的时候密码无效让他重新绑定
                this.showBind = true
                break;
              case 1084:
                console.log('请求限速')
                break;
              case 1085:
                console.log('需要手机验证码')
                // 用户刚进来的的时候密码无效让他重新绑定
                this.showBind = true
                break;          
              default:
                break;
            }
            this.cardsStatus = res.objects[0].cards_farmer
          } else {
            // 机器人存在但是可能是不好的机器人，比如密码输入错误什么的
            // this.showBind = true
          }
          console.log(this.botId)
        } else if(res._status === 0 && res.objects.length === 0) {
          // 在这个时候这个人其实是没有ASF机器人的，所以我们需要让他重头来
          this.showBind = true
        }
      })
    },
    createBot() {
      let data = {
        'name': this.username,
        'password': this.password
      }
      createBot(data).then(res=>{
        if(res._status === 0) {
          this.timer = setInterval(() => {
            this.$toast({
                type:'loading',
                message:'正在启动挂卡机器人'
            })
            getBotStatus(res.resource_uri).then((res) => {
              this.botId = res.resource_uri
              // 大于1的时候终止轮训
              // CREATE = 0              # 创建
              // TRY_START = 1           # 尝试启动
              // RUN = 2                 # 运行中
              // SERVER_OFF = 3          # 服务器关闭
              // STOP = 4                # 停止
              // # error
              // NEED_GUARD_CODE = 1063  # 需要SteamGuardCode(邮箱验证码)
              // NEED_TWO_FACTOR = 1085  # 需要TwoFactorAuthentication(手机验证码)'
              if (res.status > 1) {
                console.log(res.status)
                switch (res.status) {
                  case 0:
                    console.log('创建')
                    break;
                  case 1:
                    console.log('尝试启动')
                    break;
                  case 2:
                    console.log('运行中')
                    clearInterval(this.timer)
                    this.CurrentGamesFarming = res.objects[0].cards_farmer.CurrentGamesFarming
                    this.timer = null;
                    break;
                  case 3:
                    console.log('服务器关闭')
                    clearInterval(this.timer)
                    this.timer = null;
                    break;
                  case 4:
                    console.log('停止')
                    clearInterval(this.timer)
                    this.timer = null;
                    break;
                  case 1005:
                    console.log('无效的密码')
                    this.showBind = true
                    // 密码无效后的操作应该是让用户再次输入密码
                    clearInterval(this.timer)
                    this.timer = null; 
                    return this.$toast({
                      message: "密码无效",
                      position: "bottom"
                    });
                  case 1084:
                    console.log('请求限速')
                    clearInterval(this.timer)
                    this.timer = null;
                    this.$toast({
                      message: "请求频率过多，请稍后再试",
                      position: "bottom"
                    });
                    break;
                  case 1063:
                    console.log('需要邮箱验证码')
                    // 这个时候应该弹出二步
                    clearInterval(this.timer)
                    this.timer = null; 
                    this.dialog_show = true
                    break;
                  case 1085:
                    console.log('需要手机验证码')
                    // 这个时候应该弹出二步
                    clearInterval(this.timer)
                    this.timer = null;
                    this.dialog_show = true
                    break;          
                  default:
                    break;
                }
              }
            });
          }, 1250);
        }
      })
    }
  }
};
</script>

<style lang="scss">
.farm-container {
  min-height: 100vh;
  overflow-y: scroll;
  .status-bar {
    display: flex;
    justify-content: space-between;
  }
  .my-status {
    margin-top: 78px;
    background-image: url('../assets/images/bg-text-pattern-winter.png');
    background-repeat: repeat;
    box-shadow: 0 0 30px rgba(204,226,255,.2);
  }
  .cards-list {
    .games-to-farm {
      display: flex;
      margin: 12px 8px;
      padding: 18px 12px;
      background-image: url('../assets/images/bg-text-pattern-winter.png');
      background-repeat: repeat;
      color: #f6f6f6;
      font-size: 14px;
      align-items: center;
      .card-main {
        padding-left: 12px;
        flex: 6;
      }
      .card-img-div {
        width: 40%;
        flex: 4;
        .card-img {
          width: 100%;
          border-radius: 6px;
          border: 1px #999 solid;
        }
      }
      .main-input {
        text-align: center;
      }
    }
  }
  .games-to-farm {
    display: flex;
    margin: 12px 8px;
    padding: 18px 12px;
    background-image: url('../assets/images/bg-text-pattern-winter.png');
    background-repeat: repeat;
    color: #f6f6f6;
    font-size: 14px;
    align-items: center;
    .card-main {
      padding-left: 12px;
      flex: 6;
    }
    .card-img-div {
      width: 40%;
      flex: 4;
      .card-img {
        width: 100%;
        border-radius: 6px;
        border: 1px #999 solid;
      }
    }
    .main-input {
      text-align: center;
    }
  }
  .inputcenter {
    margin: 10px;
    color: #000;
  }
  .van-dialog__content {
    text-align: center;
    margin: 10px;
  }
  .van-dialog__header {
    text-align: center;
    color: #ffc107;
    font-size: 24px;
    font-weight: 500;
  }
  .van-toast {
    text-align: center;
  }
  .welcome_title_import {
    font-size: 22px;
    font-weight: 700;
    display: inline-block;
    margin-bottom: 6px;
    color: #ffc220;
    border-bottom: 1px #ffc220 solid;
    padding-bottom: 6px;
  }

  .welcome_time {
    font-size: 12px;
    opacity: 0.7;
  }
  .welcome_banner {
    display: grid;
    background-color: #eee;
    width: 100%;
    margin-top: 18px;
    border-radius: 10px;
    box-shadow: 5px 5px 2px rgba(204, 226, 255, 0.2);
    img {
      border-radius: 10px;
      width: 100%;
    }
  }
  .status-bar {
    margin-top: 20px;
    text-align: left;
  }
  .now-farm {
    color: #999;
  }
}
</style>
